<template>
  <div class="member-management">
    <ReCommonTable
      ref="tableRef"
      title="Banner管理"
      :loading="loading"
      :data="tableData"
      :columns="columns"
      :search-fields="searchFields"
      :pagination="pagination"
      @search="handleSearch"
      @refresh="handleRefresh"
      @size-change="handleSizeChange"
      @current-change="handleCurrentPageChange"
      @selection-change="handleSelectionChange"
    >
      <!-- 添加按钮 -->
      <template #toolbar-add>
        <el-button
          type="primary"
          size="small"
          :icon="CirclePlus"
          @click="handleAdd"
          >添加banner
        </el-button>
      </template>
      <template #bpicurl="{ row }">
        <el-image
          :src="row.b_picurl"
          fit="cover"
          class="image-slot"
          style="width: 120px; height: auto"
        >
          <template #placeholder>
            <div class="image-slot">Loading<span class="dot">...</span></div>
          </template>
        </el-image>
      </template>
      <!-- 操作列 -->
      <template #action="{ row }">
        <el-button size="small" @click="handleView(row)"> 查看</el-button>
        <el-button size="small" @click="handleEdit(row)"> 编辑</el-button>
      </template>

      <!-- 新增按钮 -->
      <template #toolbar>
        <el-button type="primary" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>
          新增Banner
        </el-button>
      </template>
    </ReCommonTable>

    <!-- Banner查看抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      title="Banner详情"
      :size="450"
      :close-on-click-modal="false"
      class="banner-drawer"
    >
      <div v-if="currentBanner" class="banner-detail">
        <!-- Banner图片展示 -->
        <div class="banner-image-section">
          <el-image
            :src="currentBanner.b_picurl"
            style="width: 100%; height: 200px"
            fit="cover"
            :preview-src-list="[currentBanner.b_picurl]"
            class="banner-main-image"
          >
            <template #error>
              <div class="image-error">
                <el-icon>
                  <Picture />
                </el-icon>
                <span>图片加载失败</span>
              </div>
            </template>
          </el-image>

          <!-- 状态标签 -->
          <div class="status-badge">
            <el-tag
              :type="currentBanner.b_status === '1' ? 'success' : 'danger'"
              size="large"
            >
              {{ currentBanner.b_status === "1" ? "上架" : "下架" }}
            </el-tag>
          </div>
        </div>

        <!-- Banner信息卡片 -->
        <div class="banner-info-card">
          <div class="info-header">
            <h3 class="banner-title">{{ currentBanner.b_name }}</h3>
            <div class="banner-id">ID: {{ currentBanner.b_bid }}</div>
          </div>

          <div class="info-content">
            <div class="info-item">
              <div class="info-label">
                <el-icon>
                  <Link />
                </el-icon>
                跳转链接
              </div>
              <div class="info-value">
                <span v-if="currentBanner.b_path" class="link-text">
                  {{ currentBanner.b_path }}
                </span>
                <span v-else class="empty-text">未设置</span>
              </div>
            </div>

            <div class="info-item">
              <div class="info-label">
                <el-icon>
                  <Sort />
                </el-icon>
                排序权重
              </div>
              <div class="info-value">
                <el-tag type="info">{{ currentBanner.b_rank }}</el-tag>
              </div>
            </div>

            <div class="info-item">
              <div class="info-label">
                <el-icon>
                  <Calendar />
                </el-icon>
                创建时间
              </div>
              <div class="info-value">
                {{ formatTimestamp(currentBanner.b_ctime) }}
              </div>
            </div>

            <div class="info-item">
              <div class="info-label">
                <el-icon>
                  <EditPen />
                </el-icon>
                更新时间
              </div>
              <div class="info-value">
                {{ formatTimestamp(currentBanner.b_uptime) }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="drawer-footer">
          <el-button @click="drawerVisible = false">关闭</el-button>
          <el-button type="primary" @click="switchToEdit">
            <el-icon>
              <Edit />
            </el-icon>
            编辑
          </el-button>
        </div>
      </template>
    </el-drawer>

    <!-- Banner编辑/新增弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :close-on-click-modal="false"
      center
      align-center
    >
      <!-- 编辑/新增表单 -->
      <div class="banner-form-container">
        <el-form
          ref="bannerFormRef"
          :model="bannerForm"
          :rules="bannerRules"
          label-width="auto"
        >
          <el-form-item label="Banner标题" prop="b_name">
            <el-input
              v-model="bannerForm.b_name"
              placeholder="请输入Banner标题"
            />
          </el-form-item>

          <el-form-item label="跳转链接" prop="b_path">
            <el-input
              v-model="bannerForm.b_path"
              placeholder="请输入跳转链接（可选）"
            />
          </el-form-item>

          <el-form-item label="状态" prop="b_status">
            <el-select v-model="bannerForm.b_status" placeholder="请选择状态">
              <el-option label="上架" value="1" />
              <el-option label="下架" value="0" />
            </el-select>
          </el-form-item>

          <el-form-item label="排序" prop="b_rank">
            <el-input-number
              v-model="bannerForm.b_rank"
              :min="0"
              :max="999"
              placeholder="请输入排序值"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="Banner图片" prop="b_picbase64">
            <!-- 上传按钮 -->
            <el-upload
              :on-change="handleBannerChange"
              :show-file-list="false"
              action="#"
              class="avatar-uploader"
            >
              <img
                v-if="imagePreview"
                :src="imagePreview"
                alt=""
                class="avatar object-cover"
              />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="submitLoading"
            @click="handleSubmit"
          >
            <el-icon>
              <Check />
            </el-icon>
            {{ dialogMode === "add" ? "新增" : "保存" }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import { CirclePlus } from "@element-plus/icons-vue";
import {
  Plus,
  Picture,
  Link,
  Sort,
  Calendar,
  EditPen,
  Edit,
  Check,
  Close,
  Delete,
  UploadFilled
} from "@element-plus/icons-vue";
import { ReCommonTable } from "@/components/ReCommonTable";
import type {
  SearchField,
  TableColumn
} from "@/components/ReCommonTable/src/index.vue";
import {
  getBannerList,
  addBanner,
  editBanner,
  type Banner,
  type BannerListParams,
  type AddBannerParams,
  type EditBannerParams
} from "@/api/banner";

defineOptions({
  name: "BannerList"
});

// 响应式数据
const loading = ref(false);
const dialogVisible = ref(false);
const drawerVisible = ref(false);
const submitLoading = ref(false);
const tableRef = ref();
const bannerFormRef = ref();
const selectedRows = ref([]);
const currentBanner = ref<Banner | null>(null);

// 弹窗模式：view-查看，edit-编辑，add-新增
const dialogMode = ref<"view" | "edit" | "add">("view");

// 弹窗标题
const dialogTitle = computed(() => {
  switch (dialogMode.value) {
    case "view":
      return "Banner详情";
    case "edit":
      return "编辑Banner";
    case "add":
      return "新增Banner";
    default:
      return "Banner";
  }
});

// Banner表单数据
const bannerForm = ref<AddBannerParams>({
  b_name: "",
  b_path: "",
  b_picbase64: "",
  b_status: "1",
  b_rank: "0"
});

// 图片预览
const imagePreview = ref("");

// 搜索表单
const searchForm = ref<BannerListParams>({});

// 表单验证规则
const bannerRules = computed(() => ({
  b_name: [{ required: true, message: "请输入BANNER标题", trigger: "blur" }],
  b_status: [{ required: true, message: "请选择状态", trigger: "change" }],
  b_rank: [{ required: true, message: "请输入排序值", trigger: "blur" }],
  b_picbase64: [
    {
      required: dialogMode.value === "add",
      message: "请上传Banner图片",
      trigger: "change"
    }
  ]
}));

// 表格数据
const tableData = ref([]);

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
  disabled: false,
  paginationSize: "default"
});

// 搜索字段配置（根据API文档）
const searchFields: SearchField[] = [
  {
    prop: "name",
    label: "关键字",
    type: "input",
    placeholder: "请输入banner标题"
  },
  {
    prop: "status",
    label: "状态",
    type: "select",
    options: [
      { label: "上架", value: "1" },
      { label: "下架", value: "0" }
    ],
    placeholder: "请选择状态"
  }
];

// 表格列配置（根据API文档字段）
const columns: TableColumn[] = [
  {
    prop: "b_bid",
    label: "记录ID",
    width: 80,
    fixed: "left"
  },
  {
    prop: "b_name",
    label: "BANNER标题",
    showOverflowTooltip: true
  },
  {
    prop: "b_path",
    label: "跳转链接",
    width: 240
  },
  {
    prop: "b_picurl",
    label: "图片",
    width: 200,
    slot: "bpicurl"
  },
  {
    prop: "b_status",
    label: "状态",
    width: 100,
    formatter: row => (row.b_status === "1" ? "上架" : "下架")
  },
  {
    prop: "b_rank",
    label: "排序",
    sortable: true,
    width: 80
  },
  {
    prop: "b_ctime",
    label: "创建时间",
    width: 180,
    formatter: row => formatTimestamp(row.b_ctime)
  },
  {
    prop: "b_uptime",
    label: "更新时间",
    width: 180,
    formatter: row => formatTimestamp(row.b_uptime)
  },
  {
    label: "操作",
    width: 140,
    fixed: "right",
    slot: "action"
  }
];

// 格式化时间戳
const formatTimestamp = (timestamp: string) => {
  if (!timestamp || timestamp === "0") return "";
  const date = new Date(parseInt(timestamp) * 1000);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit"
  });
};

// 事件处理
const handleSearch = (searchParams: any) => {
  console.log("搜索参数:", searchParams);
  searchForm.value = searchParams;
  pagination.current = 1;
  loadData();
};

const handleRefresh = () => {
  loadData();
};

const handleSizeChange = (size: number) => {
  pagination.size = size;
  pagination.current = 1;
  loadData();
};

const handleCurrentPageChange = (current: number) => {
  pagination.current = current;
  loadData();
};

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

const handleView = (row: any) => {
  currentBanner.value = row;
  drawerVisible.value = true;
};

const handleEdit = (row: any) => {
  currentBanner.value = row;
  dialogMode.value = "edit";

  // 填充表单数据
  bannerForm.value = {
    b_name: row.b_name,
    b_path: row.b_path || "",
    b_picbase64: "", // 编辑时不需要重新上传图片，除非用户选择更换
    b_status: row.b_status,
    b_rank: row.b_rank
  };

  // 设置图片预览
  imagePreview.value = row.b_picurl;

  dialogVisible.value = true;
};

const handleAdd = () => {
  currentBanner.value = null;
  dialogMode.value = "add";

  // 重置表单
  bannerForm.value = {
    b_name: "",
    b_path: "",
    b_picbase64: "",
    b_status: "1",
    b_rank: "0"
  };

  // 清空图片预览
  imagePreview.value = "";

  dialogVisible.value = true;
};

const switchToEdit = () => {
  if (currentBanner.value) {
    drawerVisible.value = false; // 关闭抽屉
    handleEdit(currentBanner.value);
  }
};
const handleBannerChange = async (file: File) => {
  const reader = new FileReader();
  reader.onload = e => {
    const base64 = e.target?.result as string;
    bannerForm.value.b_picbase64 = base64;
    imagePreview.value = base64;
  };
  reader.readAsDataURL(file.raw);
};

const removeImage = () => {
  bannerForm.value.b_picbase64 = "";
  imagePreview.value = "";
};

// 表单提交
const handleSubmit = async () => {
  if (!bannerFormRef.value) return;

  try {
    await bannerFormRef.value.validate();
    submitLoading.value = true;

    if (dialogMode.value === "add") {
      // 新增Banner
      const response = await addBanner(bannerForm.value);
      if (response.code === 1) {
        ElMessage.success(response.msg || "新增成功");
        dialogVisible.value = false;
        loadData();
      } else {
        ElMessage.error(response.msg || "新增失败");
      }
    } else if (dialogMode.value === "edit" && currentBanner.value) {
      // 编辑Banner
      const editParams: EditBannerParams = {
        b_bid: currentBanner.value.b_bid,
        b_name: bannerForm.value.b_name,
        b_path: bannerForm.value.b_path,
        b_picbase64: bannerForm.value.b_picbase64 || "", // 如果没有重新上传图片，传空字符串
        b_status: bannerForm.value.b_status,
        b_rank: bannerForm.value.b_rank
      };

      const response = await editBanner(editParams);
      if (response.code === 1) {
        ElMessage.success(response.msg || "编辑成功");
        dialogVisible.value = false;
        loadData();
      } else {
        ElMessage.error(response.msg || "编辑失败");
      }
    }
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("提交失败");
  } finally {
    submitLoading.value = false;
  }
};

// 加载数据
const loadData = async () => {
  loading.value = true;

  try {
    const params: BannerListParams = {
      num: pagination.size.toString(),
      page: pagination.current.toString(),
      ...searchForm.value
    };

    // 尝试调用API
    try {
      const response = await getBannerList(params);

      if (response.code === 1) {
        tableData.value = response.data.list;
        pagination.total = response.data.list.length; // 假设API返回的总数
        return;
      } else {
        ElMessage.error(response.msg || "数据加载失败");
      }
    } catch (apiError) {
      console.error("API调用错误:", apiError);
      ElMessage.error("数据加载失败");
    }
  } catch (error) {
    console.error("数据加载错误:", error);
    ElMessage.error("数据加载失败");
  } finally {
    loading.value = false;
  }
};

// 生命周期
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.member-management {
  height: 100%;
  background: #f5f7fa;
}

/* Banner详情抽屉样式 */
.banner-detail {
  padding: 0;
}

.banner-image-section {
  position: relative;
  margin-bottom: 20px;
}

.banner-main-image {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  background: #f5f7fa;
  color: #909399;
  font-size: 14px;
}

.image-error .el-icon {
  font-size: 48px;
  margin-bottom: 8px;
}

.status-badge {
  position: absolute;
  top: 12px;
  right: 12px;
}

.banner-info-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.info-header {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.banner-title {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
}

.banner-id {
  font-size: 12px;
  color: #909399;
  background: #f5f7fa;
  padding: 4px 8px;
  border-radius: 4px;
  display: inline-block;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}

.info-label .el-icon {
  font-size: 16px;
  color: #409eff;
}

.info-value {
  font-size: 14px;
  color: #303133;
  padding-left: 22px;
}

.link-text {
  color: #409eff;
  word-break: break-all;
}

.empty-text {
  color: #c0c4cc;
  font-style: italic;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 0 0 0;
  border-top: 1px solid #ebeef5;
}

.demo-image__placeholder.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.demo-image__placeholder .dot {
  animation: dot 2s infinite steps(3, start);
  overflow: hidden;
}

:deep(.el-image-viewer__canvas img) {
  width: 50% !important;
  height: auto;
  object-fit: cover;
}

/* Banner表单样式 */
.banner-form-container {
  padding: 0;
}

.banner-form {
  padding: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 上传组件样式 */
.upload-container {
  width: 100%;
}

.image-preview-card {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  overflow: hidden;
  background: #fff;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.preview-title {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}

.preview-image {
  border-radius: 0;
}

.banner-uploader {
  width: 100%;
}

:deep(.el-upload-dragger) {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background: #fafcff;
  transition: all 0.3s;
}

:deep(.el-upload-dragger:hover) {
  border-color: #409eff;
  background: #ecf5ff;
}

.upload-area {
  padding: 40px 20px;
  text-align: center;
}

.upload-icon {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.upload-text {
  color: #606266;
  font-size: 16px;
  margin-bottom: 8px;
}

.upload-text em {
  color: #409eff;
  font-style: normal;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  line-height: 1.4;
}

/* 抽屉样式优化 */
:deep(.banner-drawer .el-drawer__header) {
  margin-bottom: 0;
  padding: 20px 20px 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.banner-drawer .el-drawer__body) {
  padding: 20px;
}

:deep(.banner-drawer .el-drawer__footer) {
  padding: 16px 20px 20px 20px;
  border-top: 1px solid #ebeef5;
}
</style>
